package api

import (
	"github.com/gin-gonic/gin"
	"guard/internal/conf"
	"guard/internal/errors"
	"guard/internal/middleware"
	"net/http"
	"strings"
)

func login(c *gin.Context) {

	method := c.Request.Method
	sess := middleware.NewSessionCache(c.Writer, c.Request)

	switch method {
	case "GET":
		// 获取登录用户
		username := sess.GetLoginState()

		// 没有登录
		if username == "" || len(username) == 0 {
			c.HTML(http.StatusOK, "login.html", nil)
		} else {
			c.Redirect(http.StatusFound, "index.html")
		}
	case "POST":
		username := c.PostForm("username")
		password := c.PostForm("password")

		// 校验输入的账号和密码
		if len(username) < 0 || len(password) < 0 {
			_ = c.Error(errors.UsernamePasswordError)
			return
		}

		// 登录，获取用户信息
		_, userName, err := userService.Login(username, password)
		if err != nil {
			_ = c.Error(err)
			return
		}

		// 设置到session
		sess.SetLoginState(userName)

		// 获取跳转url
		goUrl := sess.Session.Get(conf.Conf.Cache.GotoUri)
		if goUrl == nil {
			c.Redirect(http.StatusFound, "index.html") // 使用301，因为301重定向是永久重定向，将会被重定向到其它页面，302更适合登录，让资源能继续使用
		} else {
			c.Redirect(http.StatusFound, goUrl.(string))
		}
	}
}

func logout(c *gin.Context) {
	// 开启session
	sess := middleware.NewSessionCache(c.Writer, c.Request)
	// 用户存在？
	username := c.GetString(conf.Conf.Cache.LoginUserKey)
	if len(username) == 0 {
		_ = c.Error(errors.OtherError("注销失败"))
		return
	}
	// 登陆了在注销
	sess.Session.Delete(conf.Conf.Cache.LoginUserKey)
	// 注销成功
	c.Redirect(http.StatusFound, "login")
}

// UserInfo header :token
func userInfo(c *gin.Context) {

	header := c.GetHeader("Authorization")
	if len(header) <= 0 {
		_ = c.Error(errors.OtherError("无效token"))
		return
	}
	tokens := strings.Split(header, " ")

	userInfoResult, err := userService.UserInfo(tokens[1])
	if err != nil {
		_ = c.Error(err)
		return
	}
	c.JSON(http.StatusOK, userInfoResult)
}
